package com.magicsoft.share.utils;

import android.content.Context;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

import java.util.Date;

/**
 * Created by lyf on 2017/9/20/020.
 * 阿里云工具类
 */

public class OssTool {
    private OSS oss;
    private Context mContext;

    private String ACCESS_ID = "LTAIC2F43El1zAj6";
    private String ACCESS_KEY = "vwpO1Y3tBwfFaUlU7yEi0U4mD7lRMD";
    private String OSS_ENDPOINT = "oss-cn-hangzhou.aliyuncs.com";


    private String BUCKET_NAME = "qixiang123";
    //    private String baseUrl = "http://wind-qixiang.oss-cn-hangzhou.aliyuncs.com/";
    private String baseUrl = "http://qixiang123.oss-cn-hangzhou.aliyuncs.com/";

    public static OssTool getInstance() {
        return OssInstance.instance;
    }


    private static class OssInstance {
        private static final OssTool instance = new OssTool();
    }

    private OssTool() {
    }

    private String bucketName;

    public OssTool init(Context context) {
        return init(context, OSS_ENDPOINT, BUCKET_NAME, ACCESS_ID, ACCESS_KEY);
    }

    /**
     * 初始化
     **/
    public OssTool init(Context context, String endpoint, String bucketName, String accessKeyId, String accessKeySecret) {
        if (oss == null) {
            mContext = context;
            OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
            oss = new OSSClient(context, endpoint, credentialProvider);
        }
        this.bucketName = bucketName;
        return OssInstance.instance;
    }

    /**
     * 普通上传，比如image
     **/
    OSSAsyncTask task;

    public void upload(final String name, String filePath, final uploadListener listener) {
        Log.d("name", name + ":" + filePath);
        // 构造上传请求
        Date date = new Date();
        final long time = date.getTime();
        PutObjectRequest put = new PutObjectRequest(bucketName, name + time + ".jpg", filePath);

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                // Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });
        task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");

                Log.d("PutObject", "UploadSuccess" + baseUrl + name + time + ".jpg");
                listener.onSuccess(baseUrl + name + time + ".jpg");

            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
                listener.onFail();
            }
        });
        // task.cancel(); // 可以取消任务

        // task.waitUntilFinished(); // 可以等待直到任务完成
    }

    public void cancel() {
        task.cancel();
    }

    public interface uploadListener {
        void onSuccess(String url);

        void onFail();
    }
}
